﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel;
using System.Linq.Expressions;
using NexTrackDesktop.NexTrack;
using System.Collections.ObjectModel;

namespace NexTrackDesktop.ViewModels
{
    /// <summary>
    /// This class is for linking events between the various views and ViewModels
    /// </summary>
    public abstract class ViewModelBase : INPCBase
    {
        static public IClient Client { get; set; }
    }

    public abstract class INPCBase : INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;

        protected void NotifyPropertyChanged<T>(Expression<Func<T>> property)
        {
            if (PropertyChanged != null)
            {
                string propertyName = GetPropertyName(property);
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
            }
        }

        private string GetPropertyName<T>(Expression<Func<T>> property)
        {
            var lambda = (LambdaExpression)property;

            MemberExpression memberExpression;
            if (lambda.Body is UnaryExpression)
            {
                var unaryExpression = (UnaryExpression)lambda.Body;
                memberExpression = (MemberExpression)unaryExpression.Operand;
            }
            else
            {
                memberExpression = (MemberExpression)lambda.Body;
            }

            return memberExpression.Member.Name;
        }
    }


    public static class Extensions
    {
        public static void UpdateInPlace<T1, T2>(this ObservableCollection<T1> col, IList<T2> source, Action<T1, T2> updateFunc) where T1 : new()
        {
            while (col.Count < source.Count)
                col.Add(new T1());

            while (col.Count > source.Count)
                col.RemoveAt(col.Count - 1);

            for (int i = 0; i < source.Count; i++)
                updateFunc(col[i], source[i]);
        }
    }
}
